<?php

require_once 'Config.php';
require_once 'alipay-sdk/aop/AopClient.php';
require_once 'alipay-sdk/aop/request/AlipayTradePrecreateRequest.php';
class AlipayF2f extends Config{
    public function pay(){
        if($_POST){
            $data=$_POST;
            $data['extend_params']=['sys_service_provider_id'=>$this->partner_id];

            $aop = new AopClient ();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $this->app_id;
            $aop->rsaPrivateKey = $this->privateKey;
            $aop->alipayrsaPublicKey=$this->publicKey;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='UTF-8';
            $aop->format='json';
            $request = new AlipayTradePrecreateRequest ();
            $request->setNotifyUrl($this->url.'/ali_isv/libs/callback/notify.php');
            $request->setBizContent(json_encode($data));
            $result = $aop->execute ($request,null,$this->app_auth_token);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if(!empty($resultCode)&&$resultCode == 10000){
                echo $this->generateQRCode($result->alipay_trade_precreate_response->qr_code);
            } else {
                echo "失败";
            }
        }
    }

    //生成支付二维码
    private function generateQRCode($qr_code){
        ob_start();
        ?>
        <!doctype html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport"
                  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>支付宝当面付</title>
        </head>
        <style>
            html,body{
                height:100%;
                width:100%;
                overflow:hidden;
                margin:0;
                padding:0;
            }
            body{
                background-color: #444444;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
            }
        </style>
        <body>
        <div id="qrcode"></div>
        </body>
        <script type="text/javascript" src="../assets/js/qrcode.js"></script>
        <script type="text/javascript">
            let qrcode = new QRCode(document.getElementById("qrcode"), {
                width : 220,
                height : 220
            });
            qrcode.makeCode("<?php echo $qr_code;?>");
        </script>
        </html>
        <?php
        return ob_get_clean();
    }
}

(new AlipayF2f())->pay();